<template>
  <a-modal title="西药" :width="1000" :visible="visible" @ok="submit" @cancel="cancelAdd">
    <a-form :form="form">
      <a-row :gutter="24">
        <a-col :span="4">
          <a-form-item label="图片识别">
            <a-upload list-type="picture-card" class="avatar-uploader" :show-upload-list="false"
              action="https://zhongyi.weizi000.cn/admin/uploadFilejt" :before-upload="beforeUpload" :data="formData"
              @change="handleChange">
              <img style="width: 100%" v-if="imageUrl" :src="imageUrl" alt="avatar" />
              <div v-else>
                <a-icon :type="loading ? 'loading' : 'plus'" />
                <div class="ant-upload-text">添加</div>
              </div>
            </a-upload>
          </a-form-item>
        </a-col>
        <a-col :span="20">
          <a-form-item label="识别到到文字">
            <a-textarea auto-size style="width: 100%;min-height: 100px;" v-model="shibie" placeholder="" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-divider />
      <a-form-item label="药品图片">
        <!-- <a-upload class="swiperUpload" :action="aliOssConfig.uploadUrl" :data="formData" list-type="picture-card"
          v-decorator="['image', { rules: [{ required: true, message: '请上传轮播图！' }] }]" :file-list="fileList"
          :before-upload="beforeUpload" @change="handleImgChange">
          <div v-if="fileList.length < 8">
            <a-icon type="plus" />
            <div class="ant-upload-text">添加</div>
          </div>
        </a-upload> -->
        <uploadBox ref='upload' @success='uploadSuccess'
          v-decorator="['image', { rules: [{ required: true, message: '请上传图片！' }] }]"></uploadBox>
      </a-form-item>
      <a-row :gutter="24">
        <a-col :span="8">
          <a-form-item label="名称">
            <a-input v-decorator="['name',{ rules: [{ required: true, message: '请输入名称' }] }]" placeholder="" />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="通用名">
            <a-input v-decorator="['short',{ rules: [{ required: false, message: '请输入通用名' }] }]" />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="分类">
            <a-select v-decorator="['drugtypeid', { rules: [{ required: false, message: '请选择分类！' }] }]"
              placeholder="请选择分类！" show-search style="width: 300px" :default-active-first-option="false"
              :show-arrow="false">
              <a-select-option v-for="(item, index) in typeList" :key="item.id" :value="item.id">
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="首字母拼音">
            <a-input v-decorator="['pinyin',{ rules: [{ required: false, message: '请输入首字母拼音' }] }]" placeholder="" />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="厂家">
            <a-input v-decorator="['changjia',{ rules: [{ required: false, message: '请输入厂家' }] }]" placeholder="" />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="规格">
            <a-input v-decorator="['guige',{ rules: [{ required: false, message: '请输入规格' }] }]" placeholder="" />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="价格">
            <a-input v-decorator="['price',{ rules: [{ required: false, message: '请输入价格' }] }]" placeholder="" />
          </a-form-item>
        </a-col>
        <!--  <a-col :span="8">
          <a-form-item label="医生指数设置">
            <a-input v-decorator="['jhprice',{ rules: [{ required: false, message: '请输入医生指数设置' }] }]" placeholder="" />
          </a-form-item>
        </a-col> -->
        <a-col :span="8">
          <a-form-item label="处方药">
            <a-input v-decorator="['chufangyao',{ rules: [{ required: false, message: '请输入处方药' }] }]" placeholder="" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="适应症">
            <a-textarea auto-size v-decorator="['indications',{ rules: [{ required: false, message: '请输入适应症' }] }]" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="成分">
            <a-textarea auto-size v-decorator="['chengfen',{ rules: [{ required: false, message: '请输入成分' }] }]" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="性状">
            <a-textarea auto-size v-decorator="['xingzhuan',{ rules: [{ required: false, message: '请输入性状' }] }]" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="剂型">
            <a-textarea auto-size v-decorator="['jixing',{ rules: [{ required: false, message: '请输入剂型' }] }]" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="不良反应">
            <a-textarea auto-size v-decorator="['blfy',{ rules: [{ required: false, message: '请输入不良反应' }] }]" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="禁忌">
            <a-textarea auto-size v-decorator="['jinji',{ rules: [{ required: false, message: '请输入禁忌' }] }]" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="注意事项">
            <a-textarea auto-size v-decorator="['zhuyi',{ rules: [{ required: false, message: '请输入注意事项' }] }]" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="药物相互作用">
            <a-textarea auto-size v-decorator="['ywhxzy',{ rules: [{ required: false, message: '请输入药物相互作用' }] }]" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="毒性">
            <a-textarea auto-size v-decorator="['duxing',{ rules: [{ required: false, message: '请输入毒性' }] }]" />
          </a-form-item>
        </a-col>

        <a-col :span="24">
          <a-form-item label="批准文号">
            <a-textarea auto-size v-decorator="['pzwh',{ rules: [{ required: false, message: '请输入批准文号' }] }]" />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="用法">
            <a-select v-decorator="['yongfa', { rules: [{ required: false, message: '请选择用法！' }] }]" placeholder="请选择用法！"
              show-search style="width: 300px" :default-active-first-option="false" :show-arrow="false">
              <a-select-option v-for="(item, index) in yongfaList" :key="item.id" :value="item.id">
                {{ item.name }}
              </a-select-option>
            </a-select>
            <!-- 	<a-textarea auto-size
							v-decorator="['yongfa',{ rules: [{ required: true, message: '请输入用法' }] }]" /> -->
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="用药频次">
            <a-select v-decorator="['pinci', { rules: [{ required: false, message: '请选择用药频次！' }] }]"
              placeholder="请选择用药频次！" show-search style="width: 300px" :default-active-first-option="false"
              :show-arrow="false">
              <a-select-option v-for="(item, index) in pinci" :key="item.id" :value="item.id">
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="用量">
            <a-textarea auto-size v-decorator="['yongliang',{ rules: [{ required: false, message: '请输入用量' }] }]" />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="用量单位">
            <a-select v-decorator="['ylunit', { rules: [{ required: false, message: '请选择用量单位！' }] }]"
              placeholder="请选择用量单位！" show-search style="width: 300px" :default-active-first-option="false"
              :show-arrow="false">
              <a-select-option v-for="(item, index) in ylunit" :key="item.id" :value="item.id">
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="开药单位">
            <a-select v-decorator="['kynuit', { rules: [{ required: false, message: '请选择开药单位！' }] }]"
              placeholder="请选择开药单位！" show-search style="width: 300px" :default-active-first-option="false"
              :show-arrow="false">
              <a-select-option v-for="(item, index) in kynuit" :key="item.id" :value="item.id">
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="总量">
            <a-input v-decorator="['allnum',{ rules: [{ required: false, message: '请输入总量' }] }]" placeholder="" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="代理">
            <!-- <a-input v-decorator="['xsid',{ rules: [{ required: false, message: '' }] }]" placeholder="" /> -->
            <div v-if='salesPerson!=""' class="rowbox">
              已选择： {{salesPerson.name}}
              <a-tag color="blue" v-if="salesPerson.state==1">销售人员</a-tag>
              <a-tag color="green" v-else-if="salesPerson.state==2">外部销售</a-tag>
              <a-tag color="orange" v-else-if="salesPerson.state==3">省份代理</a-tag>
              <a-button type="primary" style="margin-left: 20px;" @click="chooseSalesPerson">更换</a-button>
              <a-button type="" style="margin-left: 20px;" @click="salesPerson=''">删除</a-button>
            </div>
            <a-button v-else type="primary" @click="chooseSalesPerson">选择</a-button>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <salesPersonBox ref='sales' @change='setSales'></salesPersonBox>
  </a-modal>
</template>

<script>
  import {
    medicineWesAdd,
    medicineList,
    medicineWesUpdate,
    medicineUseUnit
  } from '@/api/medicine'
  import salesPersonBox from '../components/salesperson'

  import uploadBox from '@/components/obsUpload/obsUploadList'

  import {
    getFormData
  } from '@/utils/aliOss/aliossUpload.js'
  import aliOssConfig from '@/utils/aliOss/config'


  const formItemLayout = {
    labelCol: {
      span: 4
    },
    wrapperCol: {
      span: 8
    },
  };
  const formTailLayout = {
    labelCol: {
      span: 4
    },
    wrapperCol: {
      span: 8,
      offset: 4
    },
  };

  export default {
    components: {
      salesPersonBox,
      uploadBox
    },
    props: {
      visible: {
        type: Boolean,
        required: true,
      }
    },
    data() {
      return {
        shibie: '',
        fileList: [],
        checkNick: false,
        formItemLayout,
        formTailLayout,
        form: this.$form.createForm(this),
        loading: false,
        imageUrl: '',
        formData: {},
        aliOssConfig: aliOssConfig,
        id: 0,
        updateflag: false,
        typeList: [],
        kynuit: [],
        pinci: [],
        ylunit: [],
        yongfaList: [], //用法选项
        salesPerson: ''
      };
    },
    created() {
      this.getType()
      this.getUnit()
    },
    methods: {
      uploadSuccess(v) {
        this.fileList = v
        let values = this.form.getFieldsValue();
        values.image = v
        this.form.setFieldsValue(values);
      },
      setSales(v) {
        this.salesPerson = v
      },
      // 选择代理
      chooseSalesPerson() {
        this.$refs.sales.visible = true
      },
      getUnit() {
        medicineUseUnit().then(res => {
          this.kynuit = res.data.kynuit
          this.pinci = res.data.pinci
          this.ylunit = res.data.ylunit
          this.yongfaList = res.data.yongfa
        })
      },
      getType() {
        medicineList().then(res => {
          this.typeList = res.data
        })
      },
      cancelAdd() {
        this.updateflag = false
        this.$emit('cancel', true)
        this.form.resetFields()
        this.fileList = []
        this.imageUrl = ''
        this.visible = false
        this.$refs.upload.fileList = []
      },
      setUpdate(formValue) {
        var that = this
        formValue.yongliang = formValue.yongliang * 1
        formValue.pinci = formValue.pinci * 1
        formValue.ylunit = formValue.ylunit * 1
        formValue.kynuit = formValue.kynuit * 1
        formValue.yongfa = formValue.yongfa * 1
        formValue.salesPerson = formValue.xsid == 0 ? '' : {
          id: formValue.xsid,
          name: formValue.xsid
        }
        that.form.setFieldsValue({
          ...formValue
        })

        var imagesArray = []
        if (formValue.image !== '') {
          imagesArray = formValue.image.split(',')
          var imagesNewArray = []
          var bannerCurrrent = -1
          for (var i = 0; i < imagesArray.length; i++) {
            imagesNewArray.push({
              url: imagesArray[i],
              name: new Date().getTime() + '.png',
              status: 'done',
              uid: (((1 + Math.random()) * 0x10000) | 0).toString(16),
            })
          }
          that.fileList = imagesNewArray
          this.$refs.upload.fileList = imagesNewArray
        }
        this.id = formValue.id
        this.updateflag = true
      },
      submit() {
        var that = this
        const {
          form: {
            validateFields
          },
        } = this

        validateFields((errors, values) => {
          if (!errors) {
            var imglist = []
            //this.aliOssConfig.uploadUrl + '/' + this.formData.key
            for (var i = 0; i < this.fileList.length; i++) {
              imglist.push(that.fileList[i].url);
            }
            values.image = imglist.join(',');
            values.price = parseFloat(values.price)
            values.jhprice = parseFloat(values.jhprice)
            values.yongliang = values.yongliang + ''
            values.pinci = values.pinci + ''
            values.ylunit = values.ylunit + ''
            values.kynuit = values.kynuit + ''
            values.yongfa = values.yongfa + ''
            values.allnum = values.allnum * 1
            values.xsid = this.salesPerson != '' ? this.salesPerson.id * 1 : 0
            if (this.updateflag) {
              values.id = this.id
              medicineWesUpdate({
                ...values,
              }).then((res) => {
                if (res.code == 0) {
                  this.fileList = []
                  this.imageUrl = ''
                  that.form.resetFields()
                  this.$refs.upload.fileList = []
                  that.$emit('ok')
                }
              })
            } else {
              medicineWesAdd({
                ...values,
              }).then((res) => {
                if (res.code == 0) {
                  this.fileList = []
                  this.imageUrl = ''
                  this.$refs.upload.fileList = []
                  that.form.resetFields()
                  that.$emit('ok')
                }
              })
            }
          }
        })
      },
      beforeUpload(file) {
        this.formData = getFormData()
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
        if (!isJpgOrPng) {
          this.$message.error('请上传图片类型文件!')
        }
        const isLt2M = file.size / 1024 / 1024 < 2
        if (!isLt2M) {
          this.$message.error('图片最大体积为2MB!')
        }
        return isJpgOrPng && isLt2M
      },
      check() {
        this.form.validateFields(err => {
          if (!err) {
            console.info('success');
          }
        });
      },
      handleChange(info) {
        if (info.file.status === 'uploading') {
          this.loading = true
          return
        }
        if (info.file.status == 'done') {
          this.loading = false
          this.shibie = info.file.response.data
          let reader = new FileReader()
          reader.readAsDataURL(info.file.originFileObj) //把目标文件转地址，文件来自于上传组件。
          let that = this
          reader.onload = function() {
            that.imageUrl = reader.result
          }
        }
      },
      handleImgChange(info) {
        if (info.file.status == "removed") {

        } else {
          var that = this;
          const isJpgOrPng = info.file.type === 'image/jpeg' || info.file.type === 'image/png'
          if (!isJpgOrPng) {
            this.$message.error('您只能上传图片类型文件!')
            return
          }
          const isLt2M = info.file.size / 1024 / 1024 < 1

          if (!isLt2M) {
            this.$message.error('图片必须小于 1MB!')
            return
          }

          if (info.file.status == "done") {
            info.fileList[info.fileList.length - 1].url = that.aliOssConfig.uploadUrl + '/' + that.formData
              .key;
          }
        }
        this.fileList = info.fileList
      },
    },
  };
</script>